package com.example.fourm.intercepter;


import com.example.fourm.common.AppResult;
import com.example.fourm.config.AppConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterception implements HandlerInterceptor {
    /**
     * 预处理
     * @return true:已登录，可以访问呢 </br> false:未登录，跳转登录
     * @throws Exception
     */
    @Value("${forum.login.url}")
    private String defaultUrl;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppConfig.USER_SESSION) != null) {
            return true;
        }
        //未登录状态
        if(!defaultUrl.startsWith("/")){
            defaultUrl = "/" + defaultUrl;
        }
        response.sendRedirect(defaultUrl);//对defaultUrl的地址进行判断开头是否含有/
        return false;
    }
}
